<?php
namespace app\index\model;

use app\common\model\SuperModel;
use app\index\model\Apis;
use app\ux\UtilCurl;
use think\Request;

class Notice extends SuperModel
{

    protected $connection = 'db_config_dragon';

    /**
     * 新建公告请求
     */
    public function doAdd(Request $request)
    {

        try {

            //拆分服务器ID
            $arr  = explode(",", input('server_id'));
            $list = [];

            foreach ($arr as $server_id) {

                $param['server_id']   = $server_id;
                $param['content']     = input('content');
                $param['issueat']     = date("Y-m-d H:i:s");
                $param['create_time'] = date("Y-m-d H:i:s");

                //判断接口调用回参
                //
                $info = $this->curlRequest($server_id, input('content'));

                $arr               = json_decode($info, true);
                $param['comments'] = (0 == $arr['code']) ? $info : $arr['msg'];
                $param['status']   = (0 == $arr['code']) ? 0 : 1;

                array_push($list, $param);
            }

            $res = $this->allowField(true)->saveAll($list);

            return ($res);

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 接口请求
     * @DateTime 2018-01-23
     * @param    [type] $mail [description]
     * @param    [type] $cid [description]
     * @return   [array] 接口请求返回
     */
    public function curlRequest($sid, $content)
    {

        try {

            $curl = new UtilCurl;
            $url  = $this->getNoticeUrlBySid($sid);
            $url .= $content;
            //dump($url);

            $rtn = $curl->get($url);
            return $rtn;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 通过服务器ID获取接口表发放地址
     */
    public function getNoticeUrlBySid($sid)
    {

        $rec = Apis::getByServerId($sid);
        return $rec->notice;
    }
}
